package com.yhy.common.core.result;

import cn.hutool.core.util.StrUtil;
import com.yhy.common.core.annotation.NotControllerResponseAdvice;
import lombok.NonNull;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice
public class GlobalResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    /**
     * @param returnType    returnType 方法返回值类型
     * @param converterType converterType
     * @return return true 才会执行beforeBodyWrite
     */
    @Override
    public boolean supports(MethodParameter returnType, @NonNull Class<? extends HttpMessageConverter<?>> converterType) {
        return returnType.getParameterType().getName().startsWith("com.yhy")
                && !returnType.getParameterType().isAssignableFrom(Result.class)
                && !returnType.hasMethodAnnotation(NotControllerResponseAdvice.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, @NonNull MediaType selectedContentType,
                                  @NonNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  @NonNull ServerHttpRequest request, @NonNull ServerHttpResponse response) {
        if (!returnType.getParameterType().isAssignableFrom(Result.class)
                && StrUtil.equalsAnyIgnoreCase(selectedContentType.toString(), MediaType.APPLICATION_JSON_VALUE)) {
            return Result.ok(body);
        }
        return body;
    }
}